package stardust.core.network;


import java.io.InputStream;


public class NetworkSessionInputStream extends InputStream
{

  private NetworkSession session;

  public NetworkSessionInputStream(NetworkSession session)
  {
    this.session = session;
  }

  public int read()
  {
    return this.session.read();
  }

  public int read(byte[] data)
  {
    return this.session.read(data, 0, data.length);
  }

  public int read(byte[] data, int offset, int len)
  {
    return this.session.read(data, offset, len);
  }

  public byte[] requiredRead(int len)
  {
    byte[] data = new byte[len];
    int b;

    for (int i = 0; i < data.length; i++)
    {
      b = this.read();

      if (b != -1)
      {
        data[i] = (byte) b;
      }
      else
      {
        throw new IllegalStateException("end of file.");
      }
    }

    return data;
  }

  public Character readChar()
  {
    byte b0;
    byte b1;

    b0 = (byte) this.session.read();

    if (b0 < 0)
    {
      return null;
      // return Character.valueOf((char) b0);
    }

    if (b0 < 0 && (b1 = (byte) this.session.read()) != -1)
    {
      return new String(new byte[]
      {
        b0, b1
      }).charAt(0);
    }
    else
    {
      return (char) b0;
    }
  }

  public String readLine()
  {
    StringBuffer buffer = new StringBuffer();
    Character c;

    while ((c = this.readChar()) != null && c != '\n')
    {
      if (c != '\r')
      {
        buffer.append(c);
      }
    }

    return c != null || (c == null && buffer.length() > 0) ? buffer.toString() : null;
  }

}
